package com.java.star.novel.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.star.novel.core.bean.Result;
import com.java.star.novel.entity.Comment;
import com.java.star.novel.mapper.CommentMapper;
import com.java.star.novel.mapper.NovelMapper;
import com.java.star.novel.no.to.CommentAddTO;
import com.java.star.novel.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.java.star.novel.core.enums.ResultCode.FAIL;

/**
 * <p>
 * 小说评论表 服务实现类
 * </p>
 *
 * @author 零限Lx
 * @since 2023-07-13
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Autowired
    private NovelMapper novelMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addComment(Long novelId, CommentAddTO commentAddTO) throws Exception {
        // 根据小说id查询用户评论该小说的总次数
        int commentCount = this.baseMapper.countCommentsByNovelId(novelId);
        if (commentCount >= 5) {
            return new Result().code(FAIL);//code：501 msg：最多只能发布5条评论
        }

        // 创建一个新的评论对象
        Comment comment = new Comment();
        comment.setNovelId(novelId);
        // 假设在这里获取当前用户的ID，这里以假设值1为例
        Long currentUserId = 1L;
        comment.setUserId(currentUserId);
        comment.setContent(commentAddTO.getComment());

        // 保存评论信息
        this.save(comment);

        // 更新小说的评论数
        novelMapper.incrementCommentCount(novelId);
        return Result.ok();

    }
}
